package photo

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/types/forum"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreatePhotoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreatePhotoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePhotoLogic {
	return &CreatePhotoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreatePhotoLogic) CreatePhoto(in *forum.PostInfo) (*forum.BaseIDResp, error) {
	if in.Author == nil || in.Author.Id == nil || *in.Author.Id == 0 {
		return nil, resultx.StatusError(resultx.FORUM_POST_AUTHOR_ID_INVALID, "")
	}

	if len(in.NewMedia) == 0 {
		return nil, resultx.StatusError(resultx.FORUM_POST_PHOTO_REQUIRED, "")
	}

	userId := *in.Author.Id
	now := time.Now() // 本地时间
	gmtNow := modelx.GetGmtTime(now)
	post := &model.ForumPost{
		PostAuthorID:     userId,
		PostDate:         now,
		PostDateGMT:      gmtNow,
		PostModifiedDate: now,
		PostModifiedGMT:  gmtNow,
		PostStatus:       uint8(globalkey.StatusPending),
	}
	if in.ForumId != nil && *in.ForumId > 0 {
		post.ForumID = *in.ForumId
	}
	if in.TopicId != nil && *in.TopicId > 0 {
		post.TopicID = *in.TopicId
	}
	if in.ParentId != nil && *in.ParentId > 0 {
		post.ParentID = *in.ParentId
	}
	if in.CommentStatus != nil {
		post.CommentStatus = uint8(*in.CommentStatus)
	}
	if in.Author.Name != nil {
		post.PostAuthorNickname = *in.Author.Name
	}
	if in.Author.Email != nil {
		post.PostAuthorEmail = *in.Author.Email
	}
	if in.Author.Avatar != nil {
		post.PostAuthorAvatar = *in.Author.Avatar
	}
	if in.Author.Ip != nil {
		post.PostAuthorIP = *in.Author.Ip
	}
	if in.Author.Level != nil {
		post.PostAuthorRankID = uint8(*in.Author.Level)
	}
	if in.Author.Anonymous != nil {
		post.PostAuthorAnonymous = uint8(*in.Author.Anonymous)
	}

	rel := &model.ForumPostRel{}
	if len(in.Meta) > 0 {
		for _, v := range in.Meta {
			if v.Key == nil || v.Value == nil || len(strings.TrimSpace(*v.Key)) == 0 || len(strings.TrimSpace(*v.Value)) == 0 {
				continue
			}

			rel.Meta = append(rel.Meta, &model.ForumPostMetum{
				MetaKey:   strings.TrimSpace(*v.Key),
				MetaValue: null.StringFrom(strings.TrimSpace(*v.Value)),
			})
		}
	}

	var thumbnailId uint64
	var thumbnailUrl string
	var photoCount int
	for _, v := range in.NewMedia {
		var url string
		if v.Url != nil && len(*v.Url) > 0 { // 最终网址
			url = *v.Url
		}
		if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 { // 临时网址
			url = *v.Uri
		}
		if len(url) == 0 {
			continue
		}

		var media model.ForumAttachmentRelationship
		if v.Id != nil && len(*v.Id) > 0 {
			if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil && i > 0 {
				media.AttachmentID = uint64(i)
				if len(thumbnailUrl) == 0 && thumbnailId == 0 {
					thumbnailId = uint64(i)
				}
			}
		}
		if len(thumbnailUrl) == 0 {
			thumbnailUrl = url
		}
		if v.Uri != nil && len(*v.Uri) > 0 {
			media.AttachmentSource = *v.Uri
		}
		media.AttachmentImageURL = url
		if v.Thumbnail != nil && *v.Thumbnail > 0 {
			media.AttachmentThumbnail = uint8(*v.Thumbnail)
		}
		if v.AltText != nil && len(*v.AltText) > 0 {
			media.AttachmentImageAlt = *v.AltText
		}
		if v.Meta != nil && len(*v.Meta) > 0 {
			media.AttachmentImageMeta = *v.Meta
		}
		if v.Order != nil && *v.Order > 0 {
			media.AttachmentOrder = uint(*v.Order)
		}
		rel.Media = append(rel.Media, &media)
	}

	photoCount = len(rel.Media)
	if photoCount == 0 {
		return nil, resultx.StatusError(resultx.FORUM_POST_PHOTO_REQUIRED, "")
	}

	post.PhotoCount = uint(photoCount)

	if post.PostAuthorAnonymous == 0 {
		rel.Feed = &model.ForumFeed{
			ForumID:        post.ForumID,
			TopicID:        post.TopicID,
			AuthorID:       post.PostAuthorID,
			AuthorNickname: post.PostAuthorNickname,
			AuthorAvatar:   post.PostAuthorAvatar,
			AuthorIP:       post.PostAuthorIP,
			AuthorRankID:   post.PostAuthorRankID,
			ThumbnailID:    thumbnailId,
			ThumbnailURL:   thumbnailUrl,
			Status:         uint8(globalkey.StatusPending),
		}
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, resultx.StatusError(resultx.DB_ERROR, "")
	}

	err = l.svcCtx.Post.Insert(l.ctx, tx, post, rel)
	if err != nil {
		tx.Rollback()
		return nil, err
	}

	tx.Commit()

	return &forum.BaseIDResp{
		Id: post.PostID,
	}, nil
}
